package logs

import (
	"fmt"
	"os"
	"runtime"
	"strings"
	"time"

	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

// ZapLogs 全局变量logger
var ZapLogs *zap.Logger

func init() {
	// 设置一些基本日志格式 具体含义还比较好理解，直接看zap源码也不难懂
	encoder := zapcore.NewConsoleEncoder(zapcore.EncoderConfig{
		MessageKey:  "msg",
		LevelKey:    "level",
		EncodeLevel: zapcore.CapitalLevelEncoder,
		TimeKey:     "ts",
		EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
			enc.AppendString(t.Format("2006-01-02 15:04:05"))
		},
		CallerKey:    "file",
		EncodeCaller: zapcore.ShortCallerEncoder,
		EncodeDuration: func(d time.Duration, enc zapcore.PrimitiveArrayEncoder) {
			enc.AppendInt64(int64(d) / 1000000)
		},
	})

	level := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
		return lvl >= zapcore.DebugLevel
	})
	dir, err := os.Getwd()
	if err != nil {
		panic(err.Error())
	}
	if runtime.GOOS == "windows" {
		dir = strings.Replace(dir, "\\", "/", -1)
	}
	ws := getWriteSyncer(dir + fmt.Sprintf("/%s/%s%s", "logs", time.Now().Format("2006010215"), ".log"))

	// 最后创建具体的Logger
	core := zapcore.NewTee(
		//zapcore.NewCore(encoder, zapcore.AddSync(infoHook), infoLevel),
		zapcore.NewCore(encoder, ws, level),
	)

	ZapLogs = zap.New(core, zap.AddCaller()) // 需要传入 zap.AddCaller() 才会显示打日志点的文件名和行数, 有点小坑
}
func getWriteSyncer(fileName string) zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   fileName,
		MaxSize:    10,
		MaxBackups: 5,
		MaxAge:     7,
		Compress:   false,
	}
	defer lumberJackLogger.Close()
	return zapcore.AddSync(lumberJackLogger)
}

// func getWriter(filename string) io.Writer {
// 生成rotatelogs的Logger 实际生成的文件名 demo.log.YYmmddHH
// demo.log是指向最新日志的链接
// 保存7天内的日志，每1小时(整点)分割一次日志
// 	hook, err := rotatelogs.New(
// 		filename+".%Y%m%d%H", // 没有使用go风格反人类的format格式
// 		rotatelogs.WithLinkName(filename),
// 		rotatelogs.WithMaxAge(time.Hour*24*7),
// 		rotatelogs.WithRotationTime(time.Hour),
// 	)
// 	defer hook.Close()
// 	if err != nil {
// 		panic(err)
// 	}
// 	return hook
// }
